package com.localShare.adapter;

import android.graphics.Bitmap;
import android.net.Uri;
import android.support.v4.view.PagerAdapter;
import android.view.View;
import android.view.ViewGroup;
import android.widget.LinearLayout;

import com.localShare.R;
import com.nostra13.universalimageloader.core.DisplayImageOptions;
import com.nostra13.universalimageloader.core.ImageLoader;
import com.nostra13.universalimageloader.core.assist.ImageScaleType;
import com.nostra13.universalimageloader.core.display.FadeInBitmapDisplayer;
import com.util.TouchImageView;

import java.util.ArrayList;

/**
 * Created by 883564
 * on 2016/4/29.
 * 多图片加载适配器
 */
public class MultiImageAdapter extends PagerAdapter {
    //图片URI集合
    private final ArrayList<Uri> uris;
    //universal-image-loader框架加载图片的参数，参考于官方Demo
    private final DisplayImageOptions imageOptions;

    /**
     * 构造器
     * @param uris 图片uri集合
     */
    public MultiImageAdapter(ArrayList<Uri> uris){
        this.uris=uris;
        //加载图片参数初始化
        imageOptions=new DisplayImageOptions.Builder()
                .showImageOnLoading(R.drawable.loading)
                .showImageForEmptyUri(R.drawable.my_pic)
                .showImageOnFail(R.drawable.my_pic)
                .resetViewBeforeLoading(true)
                .cacheOnDisk(true)
                .imageScaleType(ImageScaleType.EXACTLY)
                .bitmapConfig(Bitmap.Config.RGB_565)
                .considerExifParams(true)
                .displayer(new FadeInBitmapDisplayer(300))
                .build();
    }

    /**
     * 图片数
     * @return 图片数目
     */
    @Override
    public int getCount() {
        return uris.size();
    }

    /**
     * 判断view是否等于object?
     * @param view 子View
     * @param object 对象
     * @return  ture 等于；false 不等于
     */
    @Override
    public boolean isViewFromObject(View view, Object object) {
        return view.equals(object);
    }

    /**
     * item销毁方法
     * @param container 父容器
     * @param position 索引
     * @param object 子Item
     */
    @Override
    public void destroyItem(ViewGroup container, int position, Object object) {
        //从父容器中移除子item
        container.removeView((View) object);
    }

    /**
     * 子View初始化
     * @param container 父容器
     * @param position 子View索引
     * @return 子View
     */
    @Override
    public View instantiateItem(ViewGroup container, final int position) {
        //初始化子View
        TouchImageView img = new TouchImageView(container.getContext());
        //使用框架加载图片
        ImageLoader.getInstance().displayImage(uris.get(position).toString(),img,imageOptions);
        //将子View添加到父容器
        container.addView(img, LinearLayout.LayoutParams.MATCH_PARENT, LinearLayout.LayoutParams.MATCH_PARENT);
        return img;
    }
}
